<template>
    <div class="clock-in-container-final">
        <el-row :gutter="24" style="height: 100%;">
            <el-col :span="15" style="height: 100%;">
                <el-card class="stage-card">
                    <transition name="view-fade" mode="out-in">
                        <div v-if="!isSuccess" key="video-view" class="video-view-wrapper">
                             <div 
                                class="video-container"
                                v-loading="!isSDKReady" 
                                element-loading-text="正在准备摄像头与AI引擎..."
                                element-loading-background="rgba(255,255,255,0.7)"
                            >
                                <video ref="videoRef" autoplay muted playsinline></video>
                                <div class="face-guide-overlay">
                                    <div class="guide-frame-corners">
                                        <div class="corner top-left"></div>
                                        <div class="corner top-right"></div>
                                        <div class="corner bottom-left"></div>
                                        <div class="corner bottom-right"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="feedback-display" :class="feedbackType">
                                <el-icon v-if="feedback.message"><component :is="feedbackIcon" /></el-icon>
                                <span>{{ feedback.message }}</span>
                            </div>
                        </div>
                        <div v-else key="success-view" class="success-view-wrapper">
                           <div class="success-icon-bg">
                               <el-icon :size="80" color="#fff"><SuccessFilled /></el-icon>
                           </div>
                            <h2 class="success-title">打卡成功！</h2>
                            <p class="success-time-info">
                                考勤时间：{{ new Date(clockInTime).toLocaleString() }}
                            </p>
                            <el-button @click="goBack" type="primary" size="large" round>返回工作台</el-button>
                        </div>
                    </transition>
                </el-card>
            </el-col>
  
            <el-col :span="9" style="height: 100%;">
                <div class="control-panel">
                    <el-card class="info-card profile-card">
                         <div class="profile-main">
                            <el-avatar :size="54" :src="authStore.user?.avatar" />
                            <div class="text-info">
                                <span class="user-name">{{ authStore.user?.username }} 老师</span>
                                <el-tag type="success" size="small" effect="dark" round>
                                    <el-icon :size="12" style="margin-right: 4px;"><CircleCheck /></el-icon>
                                    身份已认证
                                </el-tag>
                            </div>
                         </div>
                         <div class="time-display-prominent">
                             <div class="time-value">
                                <el-icon><Clock /></el-icon>
                                <span>{{ currentTime }}</span>
                             </div>
                             <div class="date-value">
                                <el-icon><Calendar /></el-icon>
                                <span>{{ currentDate }}</span>
                             </div>
                         </div>
                    </el-card>
  
                    <el-card class="info-card steps-card">
                        <template #header>
                            <div class="card-header">
                                <el-icon><Guide /></el-icon>
                                <span>打卡流程</span>
                            </div>
                        </template>
                        <div class="steps-wrapper">
                            <div class="step-item" :class="{'active': currentStep >= 1, 'completed': currentStep >= 2}">
                                <div class="step-icon-wrapper"><el-icon><Camera /></el-icon></div>
                                <div class="step-content">
                                    <p class="step-title">准备就绪</p>
                                    <p class="step-desc">摄像头与AI引擎已启动</p>
                                </div>
                            </div>
                            <div class="step-item" :class="{'active': currentStep >= 2, 'completed': currentStep >= 3}">
                                <div class="step-icon-wrapper"><el-icon><Aim /></el-icon></div>
                                <div class="step-content">
                                    <p class="step-title">人脸识别</p>
                                    <p class="step-desc">正在扫描与比对您的面部特征</p>
                                </div>
                            </div>
                            <div class="step-item" :class="{'active': currentStep >= 3, 'completed': currentStep >= 4}">
                                <div class="step-icon-wrapper"><el-icon><UserFilled /></el-icon></div>
                                <div class="step-content">
                                    <p class="step-title">身份确认</p>
                                    <p class="step-desc">已成功验证您的用户身份</p>
                                </div>
                            </div>
                            <div class="step-item" :class="{'active': currentStep >= 4, 'completed': currentStep >= 4}">
                                <div class="step-icon-wrapper"><el-icon><Select /></el-icon></div>
                                <div class="step-content">
                                    <p class="step-title">打卡成功</p>
                                    <p class="step-desc">您的考勤信息已成功记录</p>
                                </div>
                            </div>
                        </div>
                    </el-card>
                </div>
            </el-col>
        </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount, computed, reactive } from 'vue';
  import * as faceapi from 'face-api.js';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import { useAuthStore } from '../../stores/authStore';
  import profileService from '../../services/profileService';
  import attendanceService from '../../services/attendanceService';
  import { Camera, Aim, UserFilled, Select, SuccessFilled, CircleCheck, Calendar, Clock, Guide, WarningFilled, CircleCloseFilled, InfoFilled } from '@element-plus/icons-vue';
  
  // --- 核心业务逻辑与之前版本完全一致 ---
  const router = useRouter();
  const authStore = useAuthStore();
  const videoRef = ref(null);
  const isSDKReady = ref(false);
  const statusText = ref('准备中');
  const isSuccess = ref(false);
  const clockInTime = ref(null);
  // 【恢复】引入响应式 feedback 对象
  const feedback = reactive({ message: '', type: 'info' });
  
  let stream = null;
  let faceMatcher = null;
  let checkInterval = null;
  const ssdMobilenetv1Options = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.5 });
  
  const currentStep = computed(() => {
    if(isSuccess.value) return 4;
    if(statusText.value === '识别成功') return 3;
    if(statusText.value === '正在识别...') return 2;
    if(isSDKReady.value) return 1;
    return 0;
  });
  
  // 【恢复】用于UI反馈的计算属性
  const feedbackType = computed(() => feedback.type);
  const feedbackIcon = computed(() => {
    switch(feedback.type) {
        case 'success': return SuccessFilled;
        case 'error': return CircleCloseFilled;
        case 'warning': return WarningFilled;
        default: return InfoFilled;
    }
  });
  
  const currentTime = ref('');
  const currentDate = ref('');
  let timeInterval = null;
  
  const updateTime = () => {
    const now = new Date();
    currentDate.value = now.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
    currentTime.value = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
  };
  
  onMounted(async () => {
    updateTime();
    timeInterval = setInterval(updateTime, 1000);
    await loadModelsAndMatcher();
    if (isSDKReady.value && faceMatcher) {
        await startWebcam();
        if (stream) {
            checkInterval = setInterval(runCheck, 2000);
        }
    }
  });
  
  onBeforeUnmount(() => {
    if(checkInterval) clearInterval(checkInterval);
    if(timeInterval) clearInterval(timeInterval);
    stopWebcam();
  });
  
  const loadModelsAndMatcher = async () => {
    try {
        const MODEL_URL = '/models';
        await Promise.all([
            faceapi.nets.ssdMobilenetv1.loadFromUri(MODEL_URL),
            faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL),
            faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL),
        ]);
        isSDKReady.value = true;
        statusText.value = "准备就绪";
        feedback.message = "请将面部对准识别区域中央";
        feedback.type = "info";
        
        const profile = await profileService.getProfile();
        const currentUsername = authStore.user?.username;
  
        if (!profile.faceDescriptor || !currentUsername) {
            statusText.value = '档案缺失';
            feedback.message = '错误：未找到您的人脸档案，请先去录入';
            feedback.type = 'error';
            ElMessage.error('您尚未录入人脸信息，无法进行打卡。');
            isSDKReady.value = false;
            return;
        }
        const descriptor = new Float32Array(JSON.parse(profile.faceDescriptor));
        const labeledDescriptor = new faceapi.LabeledFaceDescriptors(currentUsername, [descriptor]);
        faceMatcher = new faceapi.FaceMatcher(labeledDescriptor, 0.5);
    } catch (error) {
        statusText.value = '初始化失败';
        feedback.message = 'AI引擎或个人档案加载失败';
        feedback.type = 'error';
        ElMessage.error(feedback.message + ': ' + error.message);
    }
  };
  
  const startWebcam = async () => {
    try {
        stream = await navigator.mediaDevices.getUserMedia({ video: {} });
        if (videoRef.value) videoRef.value.srcObject = stream;
    } catch (error) {
        ElMessage.error('无法启动摄像头，请检查设备和浏览器权限');
    }
  };
  
  const stopWebcam = () => {
    stream?.getTracks().forEach(track => track.stop());
  };
  
  // 【恢复】完整的 runCheck 逻辑
  const runCheck = async () => {
    if (!videoRef.value || isSuccess.value || !faceMatcher || !isSDKReady.value) return;
    statusText.value = "正在识别...";
    feedback.message = "正在进行扫描与身份比对...";
    feedback.type = "info";
    
    const result = await faceapi.detectSingleFace(videoRef.value, ssdMobilenetv1Options).withFaceLandmarks().withFaceDescriptor();
  
    if (result) {
        const bestMatch = faceMatcher.findBestMatch(result.descriptor);
        if (bestMatch.label === authStore.user?.username) {
            statusText.value = '识别成功';
            feedback.message = `验证通过 (相似度: ${(1 - bestMatch.distance).toFixed(2)})`;
            feedback.type = "success";
            clearInterval(checkInterval);
            await handleSuccess();
        } else {
            statusText.value = '身份不匹配';
            feedback.message = "错误：非本人或相似度过低，请重试";
            feedback.type = "error";
        }
    } else {
        statusText.value = "识别失败";
        feedback.message = "警告：未在区域内检测到清晰人脸";
        feedback.type = "warning";
    }
  };
  
  const handleSuccess = async () => {
    try {
        const response = await attendanceService.clockIn("日常上班打卡");
        isSuccess.value = true;
        clockInTime.value = response.data.clockInTime;
        statusText.value = "打卡成功";
        stopWebcam();
    } catch (error) {
        ElMessage.error(error.message);
        statusText.value = "准备就绪";
        checkInterval = setInterval(runCheck, 2000);
    }
  };
  
  const goBack = () => {
    router.push({ name: 'TeacherDashboard' });
  };
  </script>
  
  <style scoped>
  @keyframes success-pop-in {
    from { transform: scale(0.7) translateY(20px); opacity: 0; }
    to { transform: scale(1) translateY(0); opacity: 1; }
  }
  
  .clock-in-container-final {
  padding: 8px;
  height: calc(100vh - 84px);
  background-color: #f7f8fc;
  }
  .el-row {
    height: 100%;
  }
  
  /* 左侧主操作区 */
  .stage-card {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .video-view-wrapper, .success-view-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 24px;
    width: 100%;
  }
  .video-container {
  position: relative;
  width: 90%; 
  max-width: 640px;
  aspect-ratio: 4 / 3;
  background-color: #000;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(0,0,0,0.08);
  }
  video { width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); }
  .face-guide-overlay {
  position: absolute; top: 0; left: 0;
  width: 100%; height: 100%;
  display: flex; align-items: center; justify-content: center;
  pointer-events: none;
  }
  .guide-frame-corners {
    position: absolute; width: 50%; height: 66%;
  }
  .guide-frame-corners .corner {
    position: absolute; width: 28px; height: 28px;
    border: 5px solid #fff;
    opacity: 0.7;
  }
  .corner.top-left { top: 0; left: 0; border-right: none; border-bottom: none; border-top-left-radius: 8px; }
  .corner.top-right { top: 0; right: 0; border-left: none; border-bottom: none; border-top-right-radius: 8px;}
  .corner.bottom-left { bottom: 0; left: 0; border-right: none; border-top: none; border-bottom-left-radius: 8px;}
  .corner.bottom-right { bottom: 0; right: 0; border-left: none; border-top: none; border-bottom-right-radius: 8px;}
  
  /* 【新增】反馈信息栏 */
  .feedback-display {
    width: 90%;
    max-width: 640px;
    padding: 12px 20px;
    border-radius: 10px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    color: #fff;
    min-height: 46px;
  }
  .feedback-display.info { background-color: var(--el-color-primary); }
  .feedback-display.success { background-color: var(--el-color-success); }
  .feedback-display.warning { background-color: var(--el-color-warning); }
  .feedback-display.error { background-color: var(--el-color-error); }
  
  
  /* 成功视图 */
  .success-view-wrapper {
    animation: success-pop-in 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  }
  .success-icon-bg {
    width: 140px; height: 140px; border-radius: 50%;
    background: linear-gradient(135deg, var(--el-color-success-light-3), var(--el-color-success));
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 10px 20px -5px var(--el-color-success-light-3);
  }
  .success-title { font-size: 32px; color: #303133; margin: 0; }
  .success-time-info { font-size: 16px; color: #606266; }
  
  /* 右侧控制面板 */
  .control-panel {
    display: flex;
    flex-direction: column;
    gap: 24px;
    height: 100%;
  }
  .info-card {
    border-radius: 16px;
    border: 1px solid var(--vt-c-border-color);
  }
  .info-card :deep(.el-card__header) {
    font-size: 16px;
    font-weight: 600;
  }
  .profile-card {
    flex-shrink: 0;
  }
  .profile-card .profile-main {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
  }
  .profile-card .text-info { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; }
  .profile-card .user-name { font-size: 18px; font-weight: 600; color: #303133; }
  .time-display-prominent {
    background-color: #f4f5f9;
    padding: 16px;
    border-radius: 12px;
    text-align: center;
  }
  .time-display-prominent .time-value {
    display: flex; align-items: center; justify-content: center; gap: 8px;
    font-size: 32px;
    font-weight: bold;
    color: var(--el-color-primary);
    line-height: 1;
    margin-bottom: 8px;
  }
  .time-display-prominent .date-value {
    display: flex; align-items: center; justify-content: center; gap: 8px;
    font-size: 14px;
    color: #606266;
  }
  
  /* 步骤引导 */
  .steps-card {
    flex-grow: 1;
  }
  .steps-card .card-header { display: flex; align-items: center; gap: 8px; }
  .steps-wrapper { 
    position: relative; display: flex; flex-direction: column; 
    height: 100%;
    justify-content: space-around;
  }
  .steps-wrapper::before {
    content: '';
    position: absolute;
    left: 20px; top: 24px; bottom: 24px;
    width: 2px;
    background-color: #e4e7ed;
    transition: background-color 0.4s ease;
  }
  .step-item { display: flex; align-items: center; gap: 16px; transition: opacity 0.4s ease; }
  .step-icon-wrapper {
    width: 42px; height: 42px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 22px;
    background-color: #e4e7ed; color: #909399;
    border: 2px solid #fff;
    z-index: 1;
    transition: all 0.4s ease;
  }
  .step-content { text-align: left; }
  .step-title { font-size: 16px; font-weight: 600; color: #909399; transition: color 0.4s ease; }
  .step-desc { font-size: 13px; color: #c0c4cc; transition: color 0.4s ease; }
  
  /* 步骤激活/完成状态 */
  .step-item.active .step-icon-wrapper {
    background-color: var(--el-color-primary-light-8); color: var(--el-color-primary);
    box-shadow: 0 0 10px var(--el-color-primary-light-5);
  }
  .step-item.active .step-title { color: #303133; }
  .step-item.active .step-desc { color: #606266; }
  .step-item.completed { opacity: 0.6; }
  .step-item.completed.active { opacity: 1; }
  .step-item.completed .step-icon-wrapper {
    background-color: var(--el-color-success-light-8); color: var(--el-color-success);
  }
  
  /* 视图切换动画 */
  .view-fade-enter-active, .view-fade-leave-active {
  transition: all 0.4s ease;
  }
  .view-fade-enter-from, .view-fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
  }
  </style>